#!/bin/sh

# OpenLDAP Server start/stop script


. /etc/default/slapd

PID_FILE=/var/run/openldap/slapd.pid
EXEC=/usr/sbin/slapd


# re-create /var/run/openldap directory
if [ ! -d /var/run/openldap ]; then
  mkdir -p /var/run/openldap
  chown ldap:ldap /var/run/openldap
fi


slapd_start() {

  echo -n "Starting OpenLDAP server..."

  if [ -e $PID_FILE ]; then

    if ps axc | grep slapd >/dev/null 2>&1 ; then
      echo "already running!"
      return 1
    else
      rm $PID_FILE
    fi

  fi

  $EXEC -u ldap -h "$SLAPD_URLS" $SLAPD_OPTIONS > /dev/null 2>&1
  echo "done!"

}


slapd_stop() {

  echo -n "Stopping OpenLDAP server..."

  if [ -e $PID_FILE ]; then
    if ps axc | grep slapd >/dev/null 2>&1; then
      kill -INT $(cat $PID_FILE)
    else
      echo "already stopped!"
    fi
  fi

  rm $PID_FILE >/dev/null 2>&1
  echo "done!"

}


slapd_restart() {
  slapd_stop
  sleep 1
  slapd_start
}


slapd_status() {

  if [ -e $PID_FILE ]; then
    if ps axc | grep slapd >/dev/null 2>&1; then
      echo "OpenLDAP is running!"
      return 0
    fi

    echo "OpenLDAP PID file exists but the service is down!"
    return 1

  else
    echo "OpenLDAP is stopped!"
    return 0
  fi

}


case "$1" in
  'start')
    slapd_start
    ;;
  'stop')
    slapd_stop
    ;;
  'restart')
    slapd_restart
    ;;
  'status')
    slapd_status
    ;;
  *)
    echo "usage $0 start|stop|restart"
esac

